//
//  Home_SearchViewController.m
//  HuaRun2
//
//  Created by admin on 17/9/6.
//  Copyright © 2017年 Sunny. All rights reserved.
//

#import "Home_SearchViewController.h"
#import "Home_Search_HisCell.h"
#import "Home_Search_NoteCell.h"
#import "Home_Search_ResCell.h"

#import "Home_Search_HisModel.h"
#import "Home_Search_NoteModel.h"
#import "Home_Search_ResModel.h"

#import "Contact_DetailViewController.h"
#import "Company_DetailViewController2.h"
#import "Meeting_DetailViewController2.h"

@interface Home_SearchViewController ()
@property (nonatomic, assign) NSInteger inputCount;     //用户输入次数，用来控制延迟搜索请求
@end

@implementation Home_SearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewInit {
    [super viewInit];
    
    self.mutArray = [NSMutableArray arrayWithCapacity:1];
    
    self.navigationItem.title = NSLocalizedString(@"all_search",nil);
    self.view.backgroundColor = RGBA(249, 249, 249, 1);
// [UIColor whiteColor];
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView registerClass:[Home_Search_HisCell class]
           forCellReuseIdentifier:@"Home_Search_HisCell"];

    [self.tableView registerClass:[Home_Search_NoteCell class]
           forCellReuseIdentifier:@"Home_Search_NoteCell"];

    [self.tableView registerClass:[Home_Search_ResCell class]
           forCellReuseIdentifier:@"Home_Search_ResCell"];
    
    [self.view addSubview:self.valueLab1];
}
    
- (void)methodBind {
    [self fetchHistoryList];
    
    [self.searchView.textField addTarget:self action:@selector(searchInTimeMethod:) forControlEvents:(UIControlEventEditingChanged)];

    weakself(ws);
    self.searchView.clickBlock = ^(id result) {
        [ws searchBtnMethod];
    };
}

- (void)layoutInit {
    
    weakself(ws);
    
    [super layoutInit];
    
    [self.valueLab1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(ws.searchView);
        make.height.mas_equalTo(20);
        make.top.mas_equalTo(ws.searchView.mas_bottom).offset(kMargin10);
    }];
    
    [self.tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(ws.view);
        make.bottom.mas_equalTo(ws.view).offset(0);
        make.top.mas_equalTo(ws.valueLab1.mas_bottom).offset(kMargin10);
    }];

}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (_isNoneHistory) {
        return 1;
    }
    
    return self.mutArray.count;
}
    
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    //如果没有记录
    if (_isNoneHistory) {
        Home_Search_NoteCell * cell = [tableView dequeueReusableCellWithIdentifier:@"Home_Search_NoteCell"
                                                                      forIndexPath:indexPath];
        cell.valueLab1.text = NSLocalizedString(@"noHistory", nil);
//        @"暂无记录";
        return cell;
    }
    
    if (self.searchType== SearchTypeHis) {
//        Home_Search_HisCell * cell = [tableView dequeueReusableCellWithIdentifier:@"Home_Search_HisCell"
//                                                                     forIndexPath:indexPath];
//        cell.hisModel = self.mutArray[indexPath.row];
        Home_Search_NoteCell * cell = [tableView dequeueReusableCellWithIdentifier:@"Home_Search_NoteCell"
                                                                      forIndexPath:indexPath];
        cell.hisModel = self.mutArray[indexPath.row];

        return cell;
    }else if (self.searchType == SearchTypeNote) {
        Home_Search_NoteCell * cell = [tableView dequeueReusableCellWithIdentifier:@"Home_Search_NoteCell"
                                                                     forIndexPath:indexPath];
        cell.noteModel = self.mutArray[indexPath.row];
        return cell;
    }else if (self.searchType == SearchTypeRes) {
    
        Home_Search_ResCell * cell = [tableView dequeueReusableCellWithIdentifier:@"Home_Search_ResCell"
                                 forIndexPath:indexPath];
        cell.resModel = self.mutArray[indexPath.row];
        return cell;
    }
    return [UITableViewCell new];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {    
    return 50;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    if (_isNoneHistory) {
        return;
    }
    
    if (_searchType == SearchTypeHis) {
        
         Home_Search_HisModel * hisModel = self.mutArray[indexPath.row];
        self.searchView.textField.text = hisModel.keyword ? hisModel.keyword : @"";
        [self fetchResultListWithKeyWord:hisModel.keyword ? hisModel.keyword : @""];
    
    }else if (_searchType == SearchTypeNote) {
        
        Home_Search_NoteModel * noteModel = self.mutArray[indexPath.row];
        self.searchView.textField.text = noteModel.name ? noteModel.name : @"";
//        [self fetchResultListWithKeyWord:noteModel.name ? noteModel.name : @""];
        [self judgePushPageWithType:noteModel.type idStr:noteModel.id];
    
    }else if (_searchType == SearchTypeRes) {
        Home_Search_ResModel * resModel = self.mutArray[indexPath.row];
        [self judgePushPageWithType:resModel.type idStr:resModel.id];
    }
    
}
    
- (void)judgePushPageWithType:(NSString *)type idStr:(NSString *)idStr{

    //如果是公司
    if ([type isEqualToString:@"account"]) {

        [self pushCompanyDetailPageWithId:idStr];
    }else if ([type isEqualToString:@"contact"]) {

        [self pushContacDetailPageWithId:idStr];
    }else if ([type isEqualToString:@"meeting"]) {

        [self pushMeetingDetailPageWithId:idStr];
    }else if ([type isEqualToString:@"all"]) {

    }
    
}
//进入联系人详情页
- (void)pushContacDetailPageWithId:(NSString *)idStr {
    Contact_DetailViewController * meetingVC = [[Contact_DetailViewController alloc] init];
    meetingVC.hidesBottomBarWhenPushed = YES;
    meetingVC.contactId = idStr;
    [self.navigationController pushViewController:meetingVC animated:YES];

}

//进入会议详情
- (void)pushMeetingDetailPageWithId:(NSString *)idStr {
    
    Meeting_DetailViewController2 * detailVC = [Meeting_DetailViewController2 new];
    detailVC.meetingId = idStr;
    detailVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:detailVC animated:YES];
}

//进入公司详情
- (void)pushCompanyDetailPageWithId:(NSString *)idStr {
    Company_DetailViewController2 * detailVC = [Company_DetailViewController2 new];
    detailVC.accountId = idStr;
    detailVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:detailVC animated:YES];
}

#pragma mark - 网络请求
    //获取搜索历史记录
- (void)fetchHistoryList {
    [NetWorkHelper cancelAllRequest];

    _searchType = SearchTypeHis;
    [self.mutArray removeAllObjects];
    
    NSString * url = [NSString stringWithFormat:@"%@%@", kBaseUrl, kHome_Search_HisUrl];
    NSDictionary * dic = @{@"type": @"all"};
    weakself(ws);
    [NetWorkHelper getWithURLString:url parameters:dic success:^(id object) {
        
        if (![object[@"code"] isEqual: kSuccessCode]) {
            [ws showAlert:object[@"msg"] ? object[@"msg"] : @"" ];

            return;
        }
        NSArray * array = [NSArray yy_modelArrayWithClass:[Home_Search_HisModel class] json:object[@"list"]];
//        ws.mutArray = array;
        [ws.mutArray addObjectsFromArray:array];
        ws.isNoneHistory = ws.mutArray.count == 0;
        
        [ws.tableView reloadData];
        
        ws.valueLab1.hidden = NO;
        ws.valueLab1.text = NSLocalizedString(@"recentSearchHistory", nil);
//        @"最近搜索记录";

    } failure:^(NSError *error) {
        
        [ws showWithText:kNetworkError];
        
    }];
     
}

//    实时搜索方法
- (void)searchInTimeMethod:(UITextField *)textField {
    NSString * str = textField.text;
    NSLog(@"str --%@==", str);
    //若搜索框内容为空，显示历史记录
    if (str.length == 0/* || [str isEqualToString:@" "]*/) {

        [self fetchHistoryList];
    }else {
        _valueLab1.hidden = YES;
        // 用户停止输入1秒后进行提示内容匹配搜索
        self.inputCount ++;
        [self performSelector:@selector(fetchNoteListWithKeyWord:)
                   withObject:@(self.inputCount) afterDelay:1.0f];
    }
}
    
//点击搜索按钮搜索方法
- (void)searchBtnMethod {
    NSString * str = self.searchView.textField.text;
    if (str.length == 0) {
        return;
    }
    [self fetchResultListWithKeyWord:str];
}

    //实时获取提示列表
- (void)fetchNoteListWithKeyWord:(NSNumber *)count {
    
    if (self.inputCount == [count integerValue]) {
        
        [NetWorkHelper cancelAllRequest];
        //因为存在延时，此方法会延时1秒后执行
        NSString * keyWord = self.searchView.textField.text;
        if (keyWord.length == 0) {
            return;
        }
        
        _searchType = SearchTypeNote;
        //    _isNoneHistory = YES;
        self.current = 1;
        NSString * url = [NSString stringWithFormat:@"%@%@", kBaseUrl,
                          kHome_Search_NoteUrl];
        NSDictionary * dic = @{@"keyword": keyWord};
        weakself(ws);
        [ws.mutArray removeAllObjects];
        
        [NetWorkHelper getWithURLString:url parameters:dic success:^(id object) {
            
            if (![object[@"code"] isEqual: kSuccessCode]) {
                [ws showAlert:object[@"msg"] ? object[@"msg"] : @"" ];
                
                return;
            }
            NSArray * array = [NSArray yy_modelArrayWithClass:[Home_Search_NoteModel class] json:object[@"list"]];
//            ws.mutArray = array;
            [ws.mutArray addObjectsFromArray:array];
            
            ws.isNoneHistory = ws.mutArray.count == 0;
            
            [ws.tableView reloadData];

            if (array.count < ws.size) {
                
                [ws.tableView hiddenFooter];
            }
            
        } failure:^(NSError *error) {
            
            [ws showWithText:kNetworkError];
            
        }];
    }
}
//    获取搜索结果
- (void)fetchResultListWithKeyWord:(NSString *)keyWord {
    [NetWorkHelper cancelAllRequest];
    // @selector 和 object 都和 延迟一致 就是 指定取消 未执行的一条或者多条的延迟方法.
//    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(fetchNoteListWithKeyWord:) object:@(self.inputCount)];
    [NSObject cancelPreviousPerformRequestsWithTarget:self];
    
    _searchType = SearchTypeRes;
    
    NSString * url = [NSString stringWithFormat:@"%@%@", kBaseUrl,
                      kHome_Search_ResultUrl];
    
    NSDictionary * dic = @{@"type": @"all",
                           @"current": @(self.current),
                           @"size": @(self.size),
                           @"keyword":keyWord};
    weakself(ws);
    [ws.mutArray removeAllObjects];
    
    [NetWorkHelper getWithURLString:url parameters:dic success:^(id object) {
        if (![object[@"code"] isEqual: kSuccessCode]) {
            [ws showAlert:object[@"msg"] ? object[@"msg"] : @"" ];

            return;
        }
        NSArray * array = [NSArray yy_modelArrayWithClass:[Home_Search_ResModel class] json:object[@"list"]];

//        ws.mutArray = ws.current == 1 ? array : [ws.mutArray arrayByAddingObjectsFromArray:array];
        
        [ws.mutArray addObjectsFromArray:array];

        ws.isNoneHistory = ws.mutArray.count == 0;
        [ws.tableView reloadData];
        
        ws.valueLab1.hidden = NO;

        NSString * text = [NSString stringWithFormat:@"%@ %ld %@", NSLocalizedString(@"homeSearchResult1", nil),
         ws.mutArray.count, NSLocalizedString(@"homeSearchResult2", nil)];
        
        ws.valueLab1.text = text;
        if (array.count >= ws.size) {
            
            [ws.tableView footerRefresh:^{
                [ws loadMoreDataWithKeyWord:keyWord];
            }];
        }else {
            [ws.tableView hiddenFooter];
        }
    } failure:^(NSError *error) {
        [ws showWithText:kNetworkError];
        
    }];

}

- (void)loadMoreDataWithKeyWord:(NSString *)keyWord {
    self.current++;
    [self fetchResultListWithKeyWord:keyWord];
}

#pragma mark getter
- (UILabel *)valueLab1 {
    if (!_valueLab1) {
//        recentSearchHistory
        
//        "homeSearchResult1
//        "homeSearchResult2
        self.valueLab1 = [UILabel new];
        _valueLab1.textAlignment = NSTextAlignmentLeft;
        _valueLab1.font = kGeneralFontSize;
        _valueLab1.textColor = [UIColor colorWithHex:@"3c3c3c"];
        _valueLab1.text = NSLocalizedString(@"recentSearchHistory", nil);
//        @"最近搜索记录";
        //        _valueLab1.backgroundColor = kRandomColor;
    }
    return _valueLab1;
}
@end
